//
//  RHMeAddUserVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/17.
//

#import "RHMeAddUserVC.h"
#import "RHMeAddUserCell.h"
#import "RHAddCommonModel.h"
#import "RHMeOrgnizationListVC.h"
#import "LCMD5Tool.h"
#import "RHMeOrgnizationModel.h"

@interface RHMeAddUserVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) QMUITextView *textView;
@end

@implementation RHMeAddUserVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"新增用户".rh_localized;
    [self createData];
    [self setupUI];
}

- (void)setupUI{
    kWeakSelf;
    QMUIButton *createBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [createBtn setTitle:@"提交".rh_localized forState:UIControlStateNormal];
    [createBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [createBtn.layer setCornerRadius:8];
    [createBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:createBtn];
    [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    [[createBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf createSubUser];
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 15)];
    _tableView.tableFooterView = self.footerView;
    [_tableView registerClass:[RHMeAddUserCell class] forCellReuseIdentifier:@"RHMeAddUserCell"];
    [self.view addSubview:_tableView];
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.bottom.equalTo(createBtn.mas_top).offset(-15);
    }];
    
    
}

//选择组织
-(void)selectOrgnization:(RHAddCommonModel*)model
{
    RHMeOrgnizationListVC *orgListVC = [[RHMeOrgnizationListVC alloc]init];
   
    kWeakSelf;
    orgListVC.selectBlock = ^(RHMeOrgnizationModel* orgModel){
        model.content = [NSString stringWithFormat:@"%ld",orgModel.orgId];
        model.enum_content = orgModel.orgName;
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:orgListVC animated:YES];
}


#pragma mark -----    //添加子用户
-(void)createSubUser
{
    [self.view endEditing:YES];
    BOOL checkIsOk = YES;
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    for (RHAddCommonModel *model in self.dataArr) {
        
        BOOL needValid = model.content.length>0;
        if (model.isRequired || needValid) {
            if ([model.tag isEqualToString:@"user_name"]) {
                //用户名校验
                NSString *userName =  model.content;
                 if(![NSString validateUserName:userName]){
                     [QMUITips showError:@"账号名称请输入3到20位数字,字母或下划线".rh_localized];
                     checkIsOk = NO;
                     break;
                 }
            }
            
            if ([model.tag isEqualToString:@"user_email"]) {
                //邮箱校验
                NSString *email =  model.content;
                 if(![NSString isValidateEmail:email]){
                     [QMUITips showError:@"邮箱格式错误".rh_localized];
                     checkIsOk = NO;
                     break;
                 }
            }
            
            if ([model.tag isEqualToString:@"user_organization"]) {
                if (model.content.length == 0) {
                    [QMUITips showError:@"请选择组织".rh_localized];
                    checkIsOk = NO;
                    break;
                }
            }
            
            if ([model.tag isEqualToString:@"user_password"]) {
                //密码校验
                NSString *password =  model.content;
                if(![NSString validatePassword:password]){
                    [QMUITips showError:@"密码长度为8 ~ 16，必须包含大写字母、小写字母和数字".rh_localized];
                    break;
                }
            }
        }
        
        
         
        if (model.content.length>0) {
            [para setObject:model.content forKey:model.key];
            if ([model.tag isEqualToString:@"user_password"]) {
                [para setObject:[LCMD5Tool md5HexDigest:model.content] forKey:model.key];
            }
            if ([model.tag isEqualToString:@"user_name"]) {
                [para setObject:model.content forKey:@"nickName"];//昵称和用户名一样
            }
        }
    }
    
    if (checkIsOk == NO) {
        return;
    }
    
    if (self.textView.text.length>0) {
        [para setObject:self.textView.text forKey:@"remark"];
    }
    

   
    [para setObject:@"business" forKey:@"platform"];
    [para setObject:@"0" forKey:@"status"];
    
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:H_addUser argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.addSeccusss) {
                    self.addSeccusss();
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:SwitchRegionSuccessNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [QMUITips showError:resultModel.message];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    return nil;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHAddCommonModel *model = self.dataArr[indexPath.row];
    RHMeAddUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHMeAddUserCell"];
    
    [cell setModel:model];
    kWeakSelf;
    cell.clickBlock = ^{
        if ([model.tag isEqualToString:@"user_organization"]) {//选择组织
            [weakSelf selectOrgnization:model];
        }

    };
    if (model.isFirst) {
        [cell setTopBorder];
    }else{
        [cell setMiddleBorder];
    }
    return cell;
}

- (UIView *)footerView{
 
    UIView *_footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,380)];
    [_footerView setBackgroundColor:CFTabViewBgColor];
    
    UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-30,300)];
    [view setBackgroundColor:UIColor.whiteColor];
    [view roundBorder:8 width:1 color:kBorderColor RectCorners:QMUIViewBorderPositionLeft|QMUIViewBorderPositionBottom|QMUIViewBorderPositionRight];
    view.layer.qmui_maskedCorners = QMUILayerMinXMaxYCorner|QMUILayerMaxXMaxYCorner;
    [_footerView addSubview:view];
    
    
    QMUILabel *lab = [[QMUILabel alloc] init];
    [lab setText:@"备注".rh_localized];
    [lab setTextAlignment:NSTextAlignmentLeft];
    [lab setFont:[UIFont systemFontOfSize:14]];
    [lab setTextColor:kCOLOR_HEX(@"3F4443")];
    [_footerView addSubview:lab];
    
    QMUITextView *textView = [[QMUITextView alloc]init];
    textView.placeholder = @"请输入备注信息".rh_localized;
    textView.backgroundColor = [UIColor colorWithHexString:@"#F4F6F9"];
    textView.placeholderColor = [UIColor colorWithHexString:@"BBBBBB"];
    textView.layer.cornerRadius = 8;
    textView.layer.masksToBounds = YES;
    textView.maximumTextLength = 100;
    [_footerView addSubview:textView];
    self.textView = textView;
    

    
    kWeakSelf;
   
    
    
    [[RACSignal merge:@[textView.rac_textSignal,RACObserve(textView, text)]]subscribeNext:^(NSString*  _Nullable text) {
       
    }];
    
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(30);
        make.top.mas_offset(15);
        make.right.mas_offset(-30);
        make.height.mas_equalTo(20);
    }];
    
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(lab);
        make.top.equalTo(lab.mas_bottom).offset(20);
        make.height.offset(110);
                
    }];
    
    
   
    return _footerView;
}

-(void)createData
{
    NSArray *datas = @[
        @{@"title":@"账号名称".rh_localized,
          @"placeHolder":@"请输入账号名称".rh_localized,
          @"isRequired":@(1),
          @"tag":@"user_name",
          @"isFirst":@(1),
          @"key":@"userName"
        },
        @{@"title":@"账号密码".rh_localized,
          @"placeHolder":@"请输入账号密码".rh_localized,
          @"isRequired":@(1),
          @"tag":@"user_password",
          @"key":@"password"
        },
        @{@"title":@"用户邮箱".rh_localized,
          @"placeHolder":@"请输入用户邮箱".rh_localized,
          @"tag":@"user_email",
          @"key":@"email"
        },
        @{@"title":@"手机号".rh_localized,
          @"placeHolder":@"请输入手机号码".rh_localized,
          @"tag":@"user_phoneNumber",
          @"key":@"phonenumber"
        },
//        @{@"title":@"角色".rh_localized,
//          @"placeHolder":@"请选择角色".rh_localized,
//          @"isSelection":@(1),
//          @"isRequired":@(1),
//          @"tag":@"user_role",
//          @"key":@""
//        },
        @{@"title":@"所属组织".rh_localized,
          @"placeHolder":@"请选择组织".rh_localized,
          @"tag":@"user_organization",
          @"isRequired":@(1),
          @"isSelection":@(1),
          @"key":@"brandId",
          @"isLast":@(1)
        }
    ];
    
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHAddCommonModel class] json:datas];
    
}
@end
